<?php

namespace addons\TfFutures\services;

use addons\TfFutures\common\models\Logs;
use addons\TfFutures\common\models\MemberLever;
use addons\TfFutures\common\models\Order as OrderModel;
use addons\TfFutures\common\models\Member;
use addons\TfFutures\common\models\Order;
use addons\TfFutures\common\models\OrderReason;
use addons\TfFutures\common\models\Setup;
use addons\TfFutures\common\models\Symbol;
use addons\TfFutures\common\models\SymbolToa;
use Carbon\Carbon;
use function Complex\theta;
use Yii;

use trade\common\service\KlineService;

class OrderService
{
    /**
     *获取用户资金概况
     * @param $memberid 用户id
     * @param  $money 用户余额
     **/
    public static function loadStatic($memberid, $money,$lever_id= NULL)
    {
        //用户持仓订单
        $order = OrderModel::find()
            ->where([
                'member_id' => $memberid,
                'state' => '持仓',
                'status' => 1,
            ])->select('sum(service_fee) as service_fee, sum(overfee) as overfee, sum(deposit) as deposit, sum(profit) as profit')
            ->one();
        //用户挂单列表
        $reason = OrderReason::find()
            ->where([
                'member_id' => $memberid,
                'state' => '挂单',
                'status' => 1,
            ])
            ->select('sum(service_fee) as service_fee, sum(deposit) as deposit')
            ->one();
        $results = [
            'order_service_fee' => empty($order->service_fee)?0.00:$order->service_fee,//手续费
            'order_overfee' => empty($order->overfee)?0.00:$order->overfee,//过夜费/延期费
            'order_deposit' => empty($order->deposit)?0.00:$order->deposit,//保证金
            'order_profit' => empty($order->profit)?0.00:$order->profit,//盈损
            'reason_service_fee' => empty($reason->service_fee)? 0.00:$reason->service_fee,//手续费
            'reason_deposit' => empty($reason->deposit)? 0.00:$reason->deposit,//保证金
            'floatpl' => $order->profit,//浮动盈亏
            'networth' => bcadd($money, $order->profit, 4),//净值
        ];

        $money = round($money,2);//用户余额四舍五入
        if($money == 0){
        	$results['chongzu'] = 0;
        }else{
        	//计算耗损，得到失足率
        	$money_qian = bcadd($results['order_service_fee'],bcadd($results['order_overfee'],$results['order_profit'],2),2);
        	$results['chongzu'] = bcdiv(bcsub($money,abs($money_qian),2),$money,2);
        	$results['chongzu'] = $results['chongzu'] == 1 
													? 100
													: round($results['chongzu'] * 100,2);
			//不能让其超过一百或者低于零										
        	if($results['chongzu'] > 100){
        		$results['chongzu'] = 100;
        	} elseif ($results['chongzu'] < 0){
        		$results['chongzu'] = 0;
        	}
        }
        //计算风险率
        if($results['networth'] && $results['order_deposit'] ==0) {
            $results['riskrate'] = '0';
        }else{
            $results['riskrate'] = bcmul(bcdiv($results['networth'], $results['order_deposit'], 4), 100, 2);
        }
        $results['blocked'] = bcadd($results['order_deposit'], $results['reason_deposit'], 4);
        $results['floatpe'] = bcadd($results['floatpl'], $money, 4);
        
        $close = Setup::find()->one();
        return $results;
    }

    /**
     * 点位模式：开仓
     * @param $userid             用户id
     * @param $symbol_code        产品code
     * @param $symbol_cmd         买卖方向
     * @param $rise_fall          买涨买跌
     * @param $price              买入价格
     * @param $volume             买入手数
     * @param $stop_profit_price  止盈点位
     * @param $stop_loss_price    止损点位
     * @param $expiration         挂单有效期
     * @return array
     */
    public static function OpenWithPoint($memberid, $symbol_code, $symbol_cmd, $rise_fall, $price, $volume, $stop_profit_point = 0, $stop_loss_point = 0, $expiration = NULL, $toaid = 0)
    {

        try {
            if ($volume < 1) {
                throw new \Exception('手数不能小于1');
            }
            list($memberModel, $member) = Member::member($memberid);


            if (empty($memberModel)) {
                throw new \Exception('用户不存在');
            }
            $symbolModel = Symbol::find()->where(['=', 'code2', $symbol_code])->one();
            if (empty($symbolModel)) {
                throw new \Exception('产品不存在');
            }
            $time1 = date('w',time());
            if($time1==0||$time1==6){
                throw new \Exception('周六,周末不支持交易');
            }

            $time       = time();
            $trade_time = explode('|',$symbolModel->trade_time);
//            判断是否在交易时间内
             if(!empty($trade_time)){
                 $trade_time = explode('|',$trade_time);
                 foreach ($trade_time as $tradetime)
                 {
                     $tradetime = explode('-',$tradetime);
                     if( count($tradetime)>1 )
                     {
                         if( $time < strtotime(date('Y-m-d ').$tradetime[0]) || $time > strtotime(date('Y-m-d ').$tradetime[1])){
                             throw new \Exception('当前不在交易时间');
                         }
                     }
                 }
             }

            if ($symbolModel->rise_fall && $symbolModel->rise_fall != 'all') {
                if (strtolower($symbolModel->rise_fall) != strtolower($rise_fall)) {
                    throw new \Exception('产品不允许当前买卖方向');
                }
            }
            if (!in_array(strtoupper($symbol_cmd),['NOW', 'GT', 'LT']) || !in_array(strtoupper($rise_fall), ['RISE', 'FALL'])) {
                throw new \Exception('买卖方向错误');
            }
            $expiration = $expiration == '0000-00-00 00:00:00'
                ? NULL
                : strtotime($expiration);
            if (strtolower($symbol_cmd) == 'now') {
                $OrderModel = new OrderModel();
            } else {
                $OrderModel = new OrderReason();
            }

            if ($toaid > 0) {
                $toaModle = SymbolToa::findOne($toaid);
                if (empty($toaModle)) {
                    throw new \Exception('期权不存在');
                }
                if ($toaModle->on_sale != 'on') {
                    throw new \Exception('期权限制交易');
                }
                if (strtotime($toaModle->sdate) < (time() + 300)) {
                    throw new \Exception('期权限制交易');
                }
                $OrderModel->expiration_toa = $toaModle->sdate;
            }

            //验证价格
            if(empty($conditionsprice)){
                OrderModel::checkPriceWithPrice($symbolModel, $symbol_cmd, $rise_fall,$price,
                    $stop_profit_price, $stop_loss_price);
            }else{
                OrderModel::checkPriceWithPrice($symbolModel, $symbol_cmd, $rise_fall,$conditionsprice,
                    $stop_profit_price, $stop_loss_price);
            }
            if (strtolower($symbol_cmd) == 'now') {
                $OrderModel->state = '持仓';//持仓
                $OrderModel->expiration = NULL;
                $OrderModel->open_time = date('Y-m-d H:i:s');
                //$OrderModel->open_price = $price;
            } else {
                $OrderModel->state = '挂单';//挂单
                $OrderModel->price = $conditionsprice;

                if($type==2){
                    $OrderModel1 = new OrderModel();
                    $sum=$OrderModel1::find()
                        ->select('sum(volume) as volume')
                        ->where(['status'=>1])
                        ->andWhere(['state'=>'持仓','symbol'=>$symbol_code,'member_id'=>$memberid,'rise_fall'=>$rise_fall])
                        ->asArray()
                        ->one();
                    //print_r($sum);die;
                    if($volume>$sum){
                        throw new \Exception('条件单平仓手数不能大于您持有本产品的手数');
                    }
                }
                if (empty($price_type)) {
                    $OrderModel->price_type = 1;
                }else{
                    $OrderModel->price_type = $price_type;
                }
                $OrderModel->type = $type;
                if ($expiration > 0) {
                    $expiration = Carbon::parse($expiration)->timestamp;
                    if (bccomp($expiration, Carbon::now()->timestamp) <= 0) {
                        throw new \Exception('有效期不能小于当前时间');
                    }
                    if (empty($conditionsprice)) {
                        throw new \Exception('条件价格不能为空');
                    }
                    if (abs(bcsub($expiration, Carbon::now()->timestamp)) < 300) {
                        throw new \Exception('有效期不能小于5分钟');
                    }
                    $OrderModel->expiration = date('Y-m-d H:i:s', $expiration);
                } else {
                    $OrderModel->expiration = NULL;
                }
            }

            $OrderModel->member_id = $memberid;
            $OrderModel->symbol = $symbol_code;
            $OrderModel->symbol_cn = $symbolModel->name;
            $OrderModel->contract_size = $symbolModel->contract_size;
            $OrderModel->rise_fall = $rise_fall;
            $OrderModel->volume = $volume;
            $OrderModel->overtime = date('Y-m-d H:i:s');

            $mylever = MemberLever::find()->where([
                'member_id'=> $memberid,
                'state'    => '正常'
            ])->one();
            if( empty($mylever) ){

                throw new \Exception('杠杆合约不存在');
            }

            $lever_id = $mylever->id;
//            echo $lever_id;die;
            if( !empty($lever_id) ){

                //股票配资的手续费和保证金
                //股票配资的手续费和保证金
                $kline                   = new KlineService();
                $ticket                  = $kline->loadTicekt($symbol_code,'tf_futures_trade');

                // Yii::$app->services->kline->prex = 'rf_addon_tf_futures_symbol';

                // $ticket = Yii::$app->services->kline->loadTicekt($symbol_code);
//                 echo "<pre>";
//                 print_r($ticket);die;
//
                $OrderModel->volume      = $volume * 100;
                $OrderModel->open_price		 = $ticket['price'];
                $shizhi                  = bcmul($ticket['price'],$OrderModel->volume,$ticket['digit']);
                $OrderModel->service_fee = bcmul($shizhi,bcdiv($symbolModel->servicefee,10000,$ticket['digit']),$ticket['digit']);
                $OrderModel->deposit     = $shizhi;

            }else{
                //期货手续费和保证金
                $OrderModel->service_fee = bcmul($volume, $symbolModel->servicefee, 4);
                $OrderModel->deposit     = bcmul($volume, $symbolModel->deposit, 4);
                $OrderModel->volume      = $volume;

            }


            //添加杠杆和T0
            $OrderModel->lever_id = $lever_id;
            $OrderModel->trade_day = $symbolModel->trade_day;
            $OrderModel->stop_profit_price = $stop_profit_price;
            $OrderModel->stop_profit_point = NULL;
            $OrderModel->stop_loss_price = $stop_loss_price;
            $OrderModel->stop_loss_point = NULL;
            $OrderModel->created_at = time();
            $OrderModel->updated_at = time();
            //判断可用保证金是否足够,需要先查询用户的杠杆用户

            //throw new \Exception(var_dump(bcadd($OrderModel->service_fee, $OrderModel->deposit)>$member->price));
            if(empty($lever_id)){
                $loadStatics = self::loadStatic($memberid, $member->price);

                if( $member->price < bcadd($loadStatics['order_deposit'],$loadStatics['reason_deposit'],4)  ){
                    throw new \Exception('可用保证金不足');
                }

                $member->price         = bcsub($member->price, $OrderModel->service_fee, 4);
                $member->price_occupy += $OrderModel->deposit;
                $member->save();
            }else{
                if( $member->price < $OrderModel->service_fee ){
                    throw new \Exception('余额不足');
                }
                if( $mylever->price < $OrderModel->deposit ){
                    throw new \Exception('配资金额不足');
                }
                $member ->price = bcsub($member->price, $OrderModel->service_fee, 4);
                $mylever->price = bcsub($mylever->price, $OrderModel->deposit, 4);
                // echo "<pre>";
                // print_r($mylever->save());exit;
                if(empty($mylever->save())){
                    return [FALSE, '配资金额扣除失败'];
                }
                if(empty($member ->save())){
                    return [FALSE, '余额扣除失败'];
                }
            }

            if (!$OrderModel->save()) {
                return [FALSE, $OrderModel->getFirstErrors()];
            }
            Logs::addLogs($member->member_id, '订单开仓', $OrderModel->service_fee, bcadd($member->price, $OrderModel->service_fee, 4), $member->price, '用户开仓，扣除手续费'. $OrderModel->service_fee);
            return [TRUE, $OrderModel->save()];
        } catch (\Exception $e) {

            return [FALSE, $e->getMessage()];
        }
    }

    /**
     * 价位模式
     * @param $userid          ：开仓 挂单   用户id
     * @param $symbol_code        产品code
     * @param $symbol_cmd         买卖方向
     * @param $rise_fall          买涨买跌
     * @param $price              买入价格
     * @param $volume             买入手数
     * @param $lever_id           杠杆合约id
     * @param $stop_profit_price  止盈价格
     * @param $stop_loss_price    止损价格
     * @param $expiration         挂单有效期
     * @return array
     */
    public static function OpenWithPrice($memberid, $symbol_code, $symbol_cmd, $rise_fall, $price, $volume,$stop_profit_price = 0, $stop_loss_price = 0, $expiration = NULL,$conditionsprice=0, $price_type = 1,$type=1,$toaid = 0)
    {
        
        try {

            if ($volume < 1) {
                throw new \Exception('手数不能小于1');
            }

            //用户信息
            list($memberModel, $member) = Member::member($memberid);
            if (empty($memberModel)) {
                throw new \Exception('用户不存在');
            }
            if($memberModel->prohibit == 2) {
                throw new \Exception('用户禁止交易');
            }
            //产品信息
            $symbolModel = Symbol::find()->where(['=', 'code', $symbol_code])->one();
            if($symbolModel->status != 1){
                throw new \Exception('该产品已下架');
            }
            if (empty($symbolModel)) {
                throw new \Exception('产品不存在');
            }

            //是否在交易时间
            $time1 = date('w',time());
            $time       = time();
            $trade_time = explode('|',$symbolModel->trade_time);
             if($time1==0||$time1==6){
                 throw new \Exception('周六,周末不支持交易');
             }
            if(count($trade_time) > 1){
                 $times = [];
                 $istrue = false;
                 foreach ($trade_time as $k => $v)
                 {
                     $times[$k] = explode('-',$v);
                     if($time > strtotime(date('Y-m-d').$times[$k][0]) && $time < strtotime(date('Y-m-d').$times[$k][1]))
                     {
                        $istrue = true;
                     }
                 }
                 if(!$istrue){
                 
                     throw new \Exception('产品不在交易时间内');
                 }
            } else {
                 $times = explode('-',$trade_time[0]);
                if($times[1] < $times[0]) {
                    $times[1] = strtotime("+1 day",strtotime(date('Y-m-d').$times[1]));
                } else {
                    $times[1] = strtotime(date('Y-m-d').$times[1]);
                }
                $times[0] = strtotime(date('Y-m-d').$times[0]);
                if ($time < $times[0] || $time > $times[1]){
                     throw new \Exception('产品不在交易时间内');
                }
            }
            //买卖方向
            if ($symbolModel->rise_fall != 'all') {
                if (strtolower($symbolModel->rise_fall) != strtolower($rise_fall)) {
                    throw new \Exception('产品不允许当前买卖方向');
                }
            }
            if (!in_array(strtoupper($symbol_cmd),['NOW', 'GT', 'LT']) || !in_array(strtoupper($rise_fall), ['RISE', 'FALL'])) {
                throw new \Exception('买卖方向错误');
            }
            $expiration = $expiration == '0000-00-00 00:00:00'
                ? NULL
                : strtotime($expiration);
            //实时行情
            $kline  = new KlineService();
            $ticket = $kline->loadTicekt($symbolModel['code'],'tf_futures_trade');
            if ($price != $ticket['price'] && $price != NULL) {

                $OrderModel = new OrderReason();
                if($price > $ticket['price']){
                    $OrderModel-> limit = 'GT';
                }else{
                    $OrderModel-> limit = 'LT';
                }


                $OrderModel->state = '挂单';//挂单
                $OrderModel->price = $price;
                if(empty($type)){
                    $OrderModel->type = 1;
                }
//                if (empty($price_type)) {
//                	$OrderModel->price_type = 1;
//                }else{
//                	$OrderModel->price_type = $price_type;
//                }
                $OrderModel->type = $type;
                if ($expiration > 0) {
                    $expiration = Carbon::parse($expiration)->timestamp;
                    if (bccomp($expiration, Carbon::now()->timestamp) <= 0) {
                        throw new \Exception('有效期不能小于当前时间');
                    }
                    if (empty($conditionsprice)) {
                        throw new \Exception('条件价格不能为空');
                    }
                    if (abs(bcsub($expiration, Carbon::now()->timestamp)) < 300) {
                        throw new \Exception('有效期不能小于5分钟');
                    }
                    $OrderModel->expiration = date('Y-m-d H:i:s', $expiration);
                } else {
                    $OrderModel->expiration = NULL;
                }


            } else {
                $OrderModel = new OrderModel();

                $OrderModel->state = '持仓';//持仓
                $OrderModel->expiration = NULL;
                $OrderModel->open_time = date('Y-m-d H:i:s');



            }

            if ($toaid > 0) {
                $toaModle = SymbolToa::findOne($toaid);
                if (empty($toaModle)) {
                    throw new \Exception('期权不存在');
                }
                if ($toaModle->on_sale != 'on') {
                    throw new \Exception('期权限制交易');
                }
                if (strtotime($toaModle->sdate) < (time() + 300)) {
                    throw new \Exception('期权限制交易');
                }
                $OrderModel->expiration_toa = $toaModle->sdate;
            }
            //验证价格
            if(empty($conditionsprice)){
                OrderModel::checkPriceWithPrice($symbolModel, $symbol_cmd, $rise_fall,$price,
                    $stop_profit_price, $stop_loss_price);
            }else{
                OrderModel::checkPriceWithPrice($symbolModel, $symbol_cmd, $rise_fall,$conditionsprice,
                    $stop_profit_price, $stop_loss_price);
            }
            if (strtolower($symbol_cmd) == 'now') {
//                $OrderModel->state = '持仓';//持仓
//                $OrderModel->expiration = NULL;
//                $OrderModel->open_time = date('Y-m-d H:i:s');
            } else {
//                $OrderModel->state = '挂单';//挂单
//                $OrderModel->limit = $symbol_cmd;
//                $OrderModel->price = $conditionsprice;
//
//				if(empty($type)){
//                    $OrderModel->type = 1;
//				}
////                if (empty($price_type)) {
////                	$OrderModel->price_type = 1;
////                }else{
////                	$OrderModel->price_type = $price_type;
////                }
//                $OrderModel->type = $type;
//                if ($expiration > 0) {
//                    $expiration = Carbon::parse($expiration)->timestamp;
//                    if (bccomp($expiration, Carbon::now()->timestamp) <= 0) {
//                        throw new \Exception('有效期不能小于当前时间');
//                    }
//                    if (empty($conditionsprice)) {
//                        throw new \Exception('条件价格不能为空');
//                    }
//                    if (abs(bcsub($expiration, Carbon::now()->timestamp)) < 300) {
//                        throw new \Exception('有效期不能小于5分钟');
//                    }
//                    $OrderModel->expiration = date('Y-m-d H:i:s', $expiration);
//                } else {
//                    $OrderModel->expiration = NULL;
//                }
            }
            if($OrderModel->state == '挂单') {
                $type_name = '用户挂单';
            } else {
                $OrderModel->overtime = date('Y-m-d H:i:s');
                $type_name = '订单开仓';
            }
            $OrderModel->order_number = 'JY'.time().rand(1000,9999);
            $OrderModel->code = $symbolModel->code;
            $OrderModel->member_id = $memberid;
            $OrderModel->symbol = $symbol_code;
            $OrderModel->symbol_cn = $symbolModel->name;
            $OrderModel->contract_size = $symbolModel->contract_size;
            $OrderModel->rise_fall = $rise_fall;
            $OrderModel->volume = $volume;
//            //实时行情
//            $kline                   = new KlineService();
//            $ticket                  = $kline->loadTicekt($symbolModel['code'],'tf_futures_trade');
            $OrderModel->volume      = $volume;//手数
            $OrderModel->open_price	 = $rise_fall == 'RISE'? round($ticket['ask'],$symbolModel->digit) : round($ticket['bid'],$symbolModel->digit);//判断是买一价还是卖一价
            $OrderModel->service_fee = bcmul($symbolModel->servicefee,$volume,2);//手续费
            $OrderModel->deposit     = bcmul($symbolModel->deposit,$volume,2    );//保证金
            $OrderModel->trade_day = $symbolModel->trade_day;
            $OrderModel->stop_profit_price = $stop_profit_price;
            $OrderModel->stop_profit_point = NULL;
            $OrderModel->stop_loss_price = $stop_loss_price;
            $OrderModel->stop_loss_point = NULL;
            $OrderModel->created_at = time();
            $OrderModel->updated_at = time();

            //判断可用保证金是否足够
            $loadStatics = self::loadStatic($memberid, $member->price);
            if( $loadStatics['networth'] < $OrderModel->service_fee || $loadStatics['networth'] < $symbolModel->deposit ) {
                throw new \Exception('可用保证金不足');
            }

            $member->price         = bcsub($member->price, bcadd($OrderModel->service_fee, $OrderModel->deposit,4),4);
            if($member->price < 0){
                throw new \Exception('余额不足');
            }
            $member->price_occupy += $OrderModel->deposit;
            $member->save();

            if(empty($member ->save())){
                return [FALSE, '余额扣除失败'];
            }

            if (empty($OrderModel->save())) {
                return [FALSE, $OrderModel->getFirstErrors()];
            }
            Logs::addLogs($member->member_id, $type_name, $OrderModel->service_fee, bcadd($member->price, $OrderModel->service_fee, 2), $member->price, '用户开仓，扣除手续费'. $OrderModel->service_fee);
            return [TRUE, $OrderModel->save()];
        } catch (\Exception $e) {

            return [FALSE, $e->getMessage()];
        }
    }

    /**
     * 价位模式订单更新 持仓 && 挂单
     * @param     $orderid  订单id
     * @param     $price    更新价格
     * @param     $volume
     * @param     $tradetype
     * @param     $tradecmd
     * @param int $tp
     * @param int $sl
     * @param     $orderid
     * @param     $comment
     * @return array
     * @throws \Exception
     */
    public static function UpdateWithPrice($orderid, $price, $stop_profit_price = 0, $stop_loss_price = 0, $expiration = NULL)
    {
        try {

            if (empty($orderid)) {
                throw new \Exception('订单不能为空');
            }
            $order = OrderModel::findOne($orderid);
            if (empty($order)) {
                $order = OrderReason::findOne($orderid);
            }
            if (empty($order)) {
                throw new \Exception('订单不存在');
            }
            if (!in_array($order->state, ['挂单', '完成', '删除', '持仓', '平仓'])) {
                throw new \Exception('订单状态不明');
            }
            if ($order->state == '平仓') {
                throw new \Exception('该订单已平仓');
            }
            if ($order->state == '完成') {
                throw new \Exception('该订单已完成');
            }
            if ($order->state == '删除') {
                throw new \Exception('该订单已删除');
            }
            $expiration = $expiration == '0000-00-00 00:00:00'
                ? NULL
                : strtotime($expiration);
            if ($order->state == '持仓') {
                //持仓只能修改止盈止损
                $price = $order->open_price;
            } else if ($order->state == '挂单') {
                if (!empty($expiration)) {
                    $expiration = Carbon::parse($expiration)->timestamp;
                    if (bccomp($expiration, Carbon::now()->timestamp) <= 0) {
                        throw new \Exception('挂单有效期不能小于当前时间');
                    }
                    if (abs(bcsub($expiration, Carbon::now()->timestamp)) < 300) {
                        throw new \Exception('挂单有效期不能小于5分钟');
                    }
                    $order->expiration = date('Y-m-d H:i:s', $expiration);
                }
            } else {
                throw new \Exception('订单状态不明');
            }
            OrderModel::checkPriceWithPrice($order->symbol_code, $order->symbol_cmd,
                $order->rise_fall, $price, $stop_profit_price, $stop_loss_price);
            $order->open_price = $price;
            $order->stop_profit_price = $stop_profit_price;
            $order->stop_loss_price = $stop_loss_price;
            if (!$order->save()) {
                return [FALSE, $order->getFirstErrors()];
            }

            return [TRUE, '成功'];
        } catch (\Exception $e) {
            return [FALSE, $e->getMessage()];
        }
    }

    /**
     * 挂单转持仓
     **/
    public static function PendingToPosition($orderid)
    {

        try {
            if (empty($orderid)) {
                throw new \Exception('订单不能为空');
            }
            $order = OrderReason::findOne($orderid);
            if (empty($order)) {
                throw new \Exception('订单不存在');
            }
            if (!in_array($order->state, ['挂单', '完成', '删除'])) {
                throw new \Exception('订单状态不明');
            }
            if ($order->state == '完成') {
                throw new \Exception('该订单已完成');
            }
            if ($order->state == '删除') {
                throw new \Exception('该订单已删除');
            }
            //将该订单添加到普通订单表
            $model = new OrderModel();
            //删除不必要的属性
            unset($order->id);
            unset($order->limit);
            unset($order->limit_num);
            unset($order->limit_num_cal);
            unset($order->limit_time);
            unset($order->limit_price);
            $model->setAttributes($order->toArray());
            $model->code = $order['code'];
            $model['open_time'] = date('Y-m-d h:i:s', time());//print_r($model);die;
            $model->created_at = date('Y-m-d h:i:s', time());
            $model->updated_at = date('Y-m-d h:i:s', time());

            $model->state = '持仓';
            if (!$model->save()) {
                return [FALSE, $model->getFirstErrors()];
            }
            $order->state = '完成';
            if (!$order->save()) {
                return [FALSE, $model->getFirstErrors()];
            }

            return [TRUE, '成功'];
        } catch (\Exception $e) {
            return [FALSE, $e->getMessage()];
        }
    }

    /**
     * 订单平仓
     * @param $orderid     订单id
     * @param $close_type  平仓价格
     * @param $close_type  平仓类型
     * @throws \Exception
     */
    public static function OrderClose($orderid, $close_price = NULL, $close_type = '手动平仓',$isadmin=false)
    {

        try {
            if (empty($orderid)) {
                throw new \Exception('订单平仓 Orderid 不能为空');
            }
            if (!in_array($close_type, ['自动平仓', '手动平仓', '强制平仓'])) {
                throw new \Exception('平仓类型错误');
            }
            $order = OrderModel::findOne($orderid);
            if (empty($order)) {
                throw new \Exception('订单不存在');
            }

            //获取产品
//            $symbol = Symbol::find()->where(["code"=>$order->symbol])->one();
            //判断是否在周末
            $time1 = date('w',time());
            if($time1==0||$time1==6){
            	 throw new \Exception('周六,周末不支持交易');
            }

            $time_in = date("H:i");
            $trade_time = $symbol->trade_time;
            //判断是否在交易时间内
       //     if(!empty($trade_time)){
       //     	//设置一种交易时间段
       //     	if(strpos($trade_time,'|') == false){
       //     		if($time_in > substr($trade_time,0,strpos($trade_time, '-')) && $time_in < trim(strrchr($trade_time, '-'),'-') ==""){
       //     			throw new \Exception('当前不在交易时间');
       //     		}
       //     	}
       //     	 //分割交易時間（设置两个交易时间段）
       //     	$time = array_filter(explode('|',$trade_time));
       // 		if( $time_in > substr($time[0],0,strpos($time[0], '-')) && $time_in < trim(strrchr($time[0], '-'),'-') || $time_in > substr($time[1],0,strpos($time[1], '-')) && $time_in < trim(strrchr($time[1], '-'),'-') == ""){
       // 			//throw new \Exception('当前不在交易时间');
    			// }
       //     }
            //计算T+N
            if ($symbol->trade_day > 0 && $close_type!='强制平仓') {
                $nowTime = Carbon::now()->parse();
                $endTime = Carbon::parse($order->open_time)->addDays($symbol->trade_day);
                if ($endTime->gt($nowTime)) {
                    throw new \Exception('该订单未到交易时间');
                }
            }
            if ($order->state == '平仓') {
                throw new \Exception('该订单已平仓');
            } else if (!in_array($order->state, ['持仓', '挂单'])) {
                throw new \Exception('订单状态不明');
            }
            //判断平仓价格是否是null
            if(empty($close_price)){
            	$kline                   = new KlineService();
                $newPrice                = $kline->loadTicekt($symbol['code'],'tf_futures_trade');

	            if (empty($newPrice)) {
	                throw new \Exception('获取实时价格失败');
	            }
	            $close_price = $newPrice['price'];
            }
            $memberModel = Member::find()
                ->where(['member_id' => $order->member_id])
                ->one();
            $symbol = Symbol::findOne(['code'=>$order->symbol]);
            $memberModel->price = bcsub(bcadd(bcadd($order->profit, $memberModel->price, 4),$order->deposit,4),bcmul($symbol->servicefee,$order->volume,4),4);
//            echo $symbol->service_fee;die;
            list($close_price, $profit) = OrderModel::computeProfit($order->symbol, $order, $close_price);
            $order->state = '平仓';
            $order->profit = $profit;
            $order->close_price = $close_price;
            $order->close_type = $close_type;
            $order->close_time = date('Y-m-d H:i:s');
            if ($order->save(false)) {
//                $memberModel = Member::find()
//                    ->where(['member_id' => $order->member_id])
//                    ->one();
//                $symbol = Symbol::findOne(['code2'=>$order->symbol]);
//                $memberModel->price = bcsub(bcadd(bcadd($order->profit, $memberModel->price, 4),$order->deposit,4),bcmul($symbol->service_fee,$order->volume,4),4);

                if ($order->profit > 0) {
                    $memberModel->price_profit = bcadd($memberModel->price_profit, $order->profit,4);
                } else {
                    $memberModel->price_loss = bcadd($memberModel->price_loss, $order->profit, 4);
                }
                $memberModel->save();
                if ($close_type == '强制平仓' && !$isadmin) {
                    Logs::addLogs($memberModel->member_id, '订单爆仓', $order->profit, bcsub($memberModel->price, $order->profit, 4), $memberModel->price, '订单爆仓盈损' . $order->profit);
                }elseif ($close_type == '强制平仓' && $isadmin){
                    Logs::addLogs($memberModel->member_id, '后台强制平仓', $order->profit, bcsub($memberModel->price, $order->profit, 4), $memberModel->price, '后台强制平仓盈损' . $order->profit);
                } else {
                    Logs::addLogs($memberModel->member_id, '订单平仓', $order->profit, bcsub($memberModel->price, $order->profit, 4), $memberModel->price, '用户平仓盈损' . $order->profit);
                }

//                //判断用户是否存在杠杆，如果存在，则将保证金返还到杠杆合约里
//                if (!empty($order->lever_id)) {
//                    //查询杠杆合约
//                    $memberLever = MemberLever::findOne($order->lever_id);
//                    $memberLever->price = bcadd($memberLever->price, $order->deposit, 4);
//                    $memberLever->save();
//                }
//                if ($order->service_fee > 0) {
//                    //计算佣金
//                    $commission_money = bcmul($order->service_fee, 0.05, 4);
//                    //先查询用户pid上级用户
//                    //查询上级信息_外面
//                    $Membermodel = MemberModel::findOne($order->member_id);
//                    //上一级信息
//                    list($modelone, $modelonemember) = Member::member($Membermodel->pid);
//
//                    if (!empty($modelone)) {
//                        $modelonemember->commission = bcadd($modelonemember->commission, $commission_money, 4);
//                        $modelonemember->commission_all = bcadd($modelonemember->commission_all, $commission_money, 4);
//                        $modelonemember->save();
//                    }
//                    //给一级代理返佣
//                    $dailiOne = Manager::findOne($Membermodel->daili);
//                    if (!empty($dailiOne)) {
//                        $dailiOne->money = bcadd($dailiOne->money, $commission_money, 4);
//                        $dailiOne->money_all = bcadd($dailiOne->money_all, $commission_money, 4);
//                        $dailiOne->save();
//                    }
//                    //给运营中心返佣
//                    $dailiTwo = Manager::findOne($dailiOne->pid);
//                    if (!empty($dailiTwo)) {
//                        $dailiTwo->money = bcadd($dailiTwo->money, $commission_money, 4);
//                        $dailiTwo->money_all = bcadd($dailiTwo->money_all, $commission_money, 4);
//                        $dailiTwo->save();
//                    }
//                    //给交易所返佣
//                    $dailiThree = Manager::findOne($dailiTwo->pid);
//                    if (!empty($dailiThree)) {
//                        $dailiThree->money = bcadd($dailiThree->money, $commission_money, 4);
//                        $dailiThree->money_all = bcadd($dailiThree->money_all, $commission_money, 4);
//                        $dailiThree->save();
//                    }
//                    //给总后台返佣
//                    $dailiFore = Manager::findOne($dailiThree->pid);
//                    if (!empty($dailiFore)) {
//                        $dailiFore->money = bcadd($dailiFore->money, $commission_money, 4);
//                        $dailiFore->money_all = bcadd($dailiFore->money_all, $commission_money, 4);
//                        $dailiFore->save();
//                    }
//                }
            } else {
                return [FALSE, $order->getFirstErrors()];
            }

            return [TRUE, $order];
        } catch (\Exception $e) {
            return [FALSE, $e->getMessage()];
        }
    }

    /**
     * 撤单
     * @param $memberid
     * @param $order_id
     * @return array
     */
    public static function KillOrder($memberid, $order_id)
    {
        try {
            $order = OrderReason::find()
                ->where(['=', 'id', $order_id])
                ->andWhere(['=', 'state', '挂单'])
                ->one();
            if (empty($order)) {
                throw new \Exception('该挂单不存在或已撤单');
            }
            if (!in_array($order->state, ['平仓', '撤单', '持仓', '挂单'])) {
                throw new \Exception('订单状态不正常');
            }
            $order->state = '撤单';
            if (!$order->save()) {
                throw new \Exception('订单状态修改失败');
            }
            //返还用户余额
            $member = Member::find()->where(['member_id'=>$memberid])->one();
            //$member = Member::findOne($memberid);
            $member->price = bcadd($member->price, $order->service_fee, 4);
            $member->price = bcadd($member->price,$order->deposit,4);
            if (!$member->save()) {
                throw new \Exception('用户手续费返还失败');
            }
            Logs::addLogs($member->member_id, '撤单', $order->service_fee, bcsub($member->price, $order->service_fee, 4), $member->price, '用户撤单，返还手续费：' . $order->service_fee);
//            if (!empty($order->lever_id)) {
//                $memberLever = MemberLever::find()
//                    ->where(['id' => $order->lever_id, 'state' => '正常'])
//                    ->one();
//                if (empty($memberLever)) {
//                    throw new \Exception('杠杆状态错误');
//                }
//                //用户存在杠杆，从杠杆合约里面扣除保证金
//                $memberLever->price = bcadd($memberLever->price, $order->deposit, 4);
//
//                if (!$memberLever->save()) {
//                    throw new \Exception('保证金返还失败');
//                }
//            }

            return [TRUE, '撤单成功'];
        } catch (\Exception $e) {

            return [FALSE, $e->getMessage()];
        }
    }

}

